package com.fortune.rainshineservice.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.base.ParmsModel;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.ProductModel;
import com.fortune.rainshinecommon.model.service.StockModel;
import com.fortune.rainshinecommon.util.StringUtil;
import com.fortune.rainshineservice.mapper.ProductMapper;
import com.fortune.rainshineservice.mapper.StockMapper;
import com.fortune.rainshineservice.mapper.StockRecordsMapper;
import com.fortune.rainshineservice.service.IproductService;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @program: rainShine
 * @description: 产品服务实现
 * @author: tangyn
 * @create: 2019-02-23
 **/
@Service
public class ProductServiceImpl implements IproductService {
    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private StockRecordsMapper stockRecordsMapper;

    @Override
    @Transactional
    public MsgModel createProduct(ProductModel productModel) {
        try {
            if (productModel.getProductPrice().compareTo(BigDecimal.ZERO) == 0) {
                return new MsgModel("招商采购价格不能为零！", ResultCode.SUCCESS);
            }
            if (productModel.getZsPrice().compareTo(BigDecimal.ZERO) == 0) {
                return new MsgModel("门店采购价格不能为零！", ResultCode.SUCCESS);
            }
//            if (productModel.getIsSale().intValue() == 1 &&
//                    (productModel.getShopPrice() == null || productModel.getShopPrice().compareTo(BigDecimal.ZERO) == 0)) {
//                return new MsgModel("门店销售价格不能为零！", ResultCode.SUCCESS);
//            }
            productModel.setCreateId(productModel.getUser().getUserId());
            productModel.setUpdateId(productModel.getUser().getUserId());
            int res = productMapper.insert(productModel);
            if (res > 0) {
                return new MsgModel("创建产品成功！", ResultCode.SUCCESS);
            } else {
                return new MsgModel("创建产品失败！", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("createProduct =====> {}", e);
            return new MsgModel("创建产品失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel updateProduct(ProductModel productModel, String userName) {
        try {
            if (productModel.getProductPrice().compareTo(BigDecimal.ZERO) == 0) {
                return new MsgModel("招商采购价格不能为零！", ResultCode.SUCCESS);
            }
            if (productModel.getZsPrice().compareTo(BigDecimal.ZERO) == 0) {
                return new MsgModel("门店采购价格不能为零！", ResultCode.SUCCESS);
            }
//            if (productModel.getIsSale().intValue() == 1 &&
//                    (productModel.getShopPrice() == null || productModel.getShopPrice().compareTo(BigDecimal.ZERO) == 0)) {
//                return new MsgModel("门店销售价格不能为零！", ResultCode.SUCCESS);
//            }
            //productModel.setUpdateId(userName);
            productMapper.updateProduct(productModel);
            return new MsgModel("更新产品成功！", ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error("updateProduct =====> {}", e);
            return new MsgModel("更新产品失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel productList(ParmsModel parm) {
        try {
            Wrapper<ProductModel> wrapper = new EntityWrapper<>();
            if (StringUtil.isNotBlank(parm.getSearchKey())) {
                wrapper.like(parm.getSearchKey(), parm.getSearchValue());
            }
            Page<ProductModel> page = new Page<>(parm.getPage(), parm.getLimit());
            List<ProductModel> list = Optional
                    .ofNullable(productMapper.selectPage(page, wrapper.orderBy("create_time", true)))
                    .orElse(Lists.newArrayList());
            if(parm.getRoleId() != null && parm.getRoleId() == 5 && !list.isEmpty()) {
            	list.forEach(e -> e.setProductPrice(e.getZsPrice()));
            }
            int total = productMapper.selectCount(wrapper);
            return new MsgModel(total, list);
        } catch (Exception e) {
            logger.error("productList ===> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    @Override
    @Transactional
    public MsgModel delProduct(ProductModel productModel) {
        try {
            //查询产品库存是否被采购过
            List<StockModel> sList = Optional.ofNullable(stockMapper.getIsSaleList(productModel.getId())).orElse(Lists.newArrayList());
            if(!sList.isEmpty()){
                return new MsgModel("该产品已被采购，不能删除！", ResultCode.FAILURE);
            }
            boolean rs = productMapper.deleteById(productModel.getId()) > 0;
            if (rs) {
                boolean r = stockMapper.deleteByProductId(productModel.getId());
                if(r){
                    boolean f = stockRecordsMapper.deleteByProductId(productModel.getId());
                    if(f){
                        return new MsgModel("删除产品成功！", ResultCode.SUCCESS);
                    }else{
                        return new MsgModel("删除库存操作记录失败！", ResultCode.FAILURE);
                    }
                }else{
                    return new MsgModel("删除库存信息失败！", ResultCode.FAILURE);
                }
            } else {
                return new MsgModel("删除产品失败！", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("delProduct ===>" + e.getMessage());
            return new MsgModel("删除产品失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel update(ProductModel productModel) {
        try {
            if (productModel.getProductPrice().compareTo(BigDecimal.ZERO) == 0) {
                return new MsgModel("招商采购价格不能为零！", ResultCode.FAILURE);
            }
            if (productModel.getZsPrice().compareTo(BigDecimal.ZERO) == 0) {
                return new MsgModel("门店采购价格不能为零！", ResultCode.FAILURE);
            }
//            if (productModel.getIsSale().intValue() == 1 &&
//                    (productModel.getShopPrice() == null || productModel.getShopPrice().compareTo(BigDecimal.ZERO) == 0)) {
//                return new MsgModel("门店销售价格不能为零！", ResultCode.SUCCESS);
//            }
            if(productModel.getSaleStatus() == 0){
                ProductModel oldProduct = productMapper.selectById(productModel.getId());
                if(oldProduct.getSaleStatus() == 1){
                    StockModel s = new StockModel();
                    s.setProductId(productModel.getId());
                    s.setShopId(1);//只有boss能对产品进行修改
                    s.setProductAmount(0);
                    s.setWarningNum(0);
                    s.setUpdateTime(new Date());
                    stockMapper.updateSelective(s);
                }
            }

            boolean rs = productMapper.updateById(productModel) > 0;
            if (rs) {
                return new MsgModel("更新产品成功！", ResultCode.SUCCESS);
            } else {
                return new MsgModel("更新产品失败！", ResultCode.FAILURE);
            }
        } catch (Exception e) {
            logger.error("update ===>" + e.getMessage());
            return new MsgModel("更新产品失败！", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel getProductInfo(Integer productId) {
        ProductModel productModel = productMapper.selectById(productId);
        return new MsgModel(ResultCode.SUCCESS, productModel);
    }

}
